package com.heima.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.vo.LoginVo;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.springframework.stereotype.Service;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        if (ObjectUtil.isEmpty(dto)){
            String token = AppJwtUtil.getToken(0L);
            return ResponseResult.okResult(LoginVo.builder().token(token).build());
        }
        ApUser user = lambdaQuery().eq(ApUser::getPhone, dto.getPhone()).one();
        if (ObjectUtil.isEmpty(user)){
            return ResponseResult.errorResult(1002,"用户不存在");
        }
        boolean checkpw = BCrypt.checkpw(dto.getPassword(), user.getPassword());
        if (!checkpw){
            return ResponseResult.errorResult(2,"用户密码错误");
        }
        String token = AppJwtUtil.getToken(user.getId().longValue());

        return ResponseResult.okResult(LoginVo.builder().user(user).token(token).build());
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
